/* Copyright (c) 2016-2020 Enfry Ltd. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Enfry. 
 * You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with Enfry.
 */
package com.enfry.storage.interceptor;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.enfry.storage.Response;
import com.enfry.storage.exception.ExCode;
import com.enfry.storage.interceptor.FileTypeProcessor;
import com.enfry.storage.interceptor.IProcessor;

/**
 * 文件类型限制。
 * @Title com.enfry.storage.interceptor.FileTypeProcessor
 * @author liulei
 * @date 2016年7月25日
 */
public class FileTypeProcessor implements IProcessor {
    private static Logger logger = LoggerFactory.getLogger(FileTypeProcessor.class);
    private List<String> allowTypes;
    
    public FileTypeProcessor() {
        allowTypes = new ArrayList<String>();
    }

    @Override
    public boolean process(HttpServletRequest request, HttpServletResponse response, Object handler, String reqApiName) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        for (Entry<String, MultipartFile> entry : multipartRequest.getFileMap().entrySet()) {
            MultipartFile file = entry.getValue();
            String filename = file.getOriginalFilename();
            String fileExtName = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
            boolean result = allowTypes.contains(fileExtName);

            if (!result) {
                ExCode exCode = ExCode.FILE_UPLOAD_TYPE_LIMIT;
                Response rep = new Response(exCode.getCode(), exCode.getMsg() + ":" + fileExtName);
                logger.debug(rep.toString());
                response.getWriter().write(rep.toString());
                return false;
            }
        }
        return true;
    }

    public void setAllowTypes(String allowTypeStrs) {
        // 去掉前后空格
        String[] types = allowTypeStrs.split(",");
        for(int i = 0; i < types.length-1; i++) {
            types[i] = types[i].trim();
        }
        this.allowTypes = Arrays.asList(types);
    }
}
